<template>
  <div
    id="subscribe"
    class="main-div"
    v-loading="p2pLoading"
  >
    <div class="my-breadcrumb-div">
      <i class="el-icon-location my-breadcrumb-icon my-breadcrumb-padding" />
      <el-breadcrumb
        class="my-breadcrumb-padding"
        separator="/"
      >
        <el-breadcrumb-item>
          <!--配置-->
          {{ $t('message.p2p.breadcrumb.crumb1') }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <!--点对点通信-->
          {{ $t('message.p2p.breadcrumb.crumb2') }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card style="height: calc(100% - 60px)">
      <div
        class="card-header-div"
        style="float: none"
      >
        <!--点对点通信-->
        {{ $t('message.p2p.card.title') }}
        <el-button
          v-if="$store.state.is_staff"
          @click="handleP2pCreate"
          style="padding: 0 0 0 5px"
          type="text"
        >
          <i
            class="el-icon-plus"
            style="font-weight: bold"
          />
        </el-button>
      </div>
      <el-table
        style="margin-top: 10px"
        height="calc(100% - 3em)"
        :data="p2pTable"
        header-cell-class-name="my-table-header-cell"
        cell-class-name="my-table-cell"
      >
        <!--终端1-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col1')"
          prop="caller_device"
        />
        <!--终端2-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col2')"
          prop="called_device"
        />
        <!--终端1速率-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col3')"
          prop="caller_speed"
        />
        <!--终端2速率-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col4')"
          prop="called_speed"
        />
        <!--卫星-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col5')"
          prop="satellite_name"
        />
        <!--终端1波束-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col6')"
          prop="caller_beam_name"
        />
        <!--终端2波束-->
        <el-table-column
          :label="$t('message.p2p.card.table.header.col7')"
          prop="called_beam_name"
        />
        <!--操作-->
        <el-table-column
          v-if="$store.state.is_staff"
          :label="$t('message.p2p.card.table.header.col8')"
        >
          <template slot-scope="scope">
            <el-button
              style="padding: 0 0 0 5px"
              @click.stop="handleP2pDelete(scope.row)"
              type="text"
            >
              <img src="@/assets/common/delete.png">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div>
      <!--添加点对点通信-->
      <el-dialog
        :title="$t('message.p2p.dialog.p2p.create.title')"
        @close="handleAddP2pDialogClose"
        top="8vh"
        width="800px"
        :close-on-click-modal="false"
        :visible.sync="addP2pVisible"
        v-loading="p2pDialogLoading"
      >
        <el-alert
          style="margin-top: 10px"
          :title="$t('message.p2p.dialog.p2p.create.alertInfo')"
          type="info"
          effect="dark"
        />
        <div class="subscribe-dialog-div-content">
          <div
            class="subscribe-dialog-div-content-item1 background-color-base"
            style="margin-right: 20px;box-sizing: border-box"
          >
            <div class="subscribe-dialog-form-header-container">
              <div class="subscribe-dialog-form-header">
                <span>
                  <!--当前信息:-->
                  {{ $t('message.p2p.dialog.p2p.create.leftForm.header') }}
                </span>
              </div>
            </div>
            <el-form
              style="height: 400px"
              class="demo-ruleform"
              :model="addP2pForm"
              ref="addP2PForm"
              :rules="addP2pFormRules"
              label-width="150px"
            >
              <!--终端1-->
              <el-form-item
                class="no-margin-bottom"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label1')"
                prop="caller.caller_cu_device"
              >
                <span>{{ addP2pForm.caller.caller_cu_device }}</span>
              </el-form-item>
              <!--终端2-->
              <el-form-item
                class="no-margin-bottom"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label2')"
                prop="called.called_cu_device"
              >
                <span>{{ addP2pForm.called.called_cu_device }}</span>
              </el-form-item>
              <!--业务类型-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.labelAdd1')"
                prop="traffic"
              >
                <el-select
                  v-model="addP2pForm.traffic"
                  value-key="value"
                >
                  <el-option
                    v-for="item in addP2pForm.traffic_option"
                    :key="item.value"
                    :label="item.label"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <!--卫星-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label3')"
                prop="satellite"
              >
                <el-select
                  @change="handleAddP2pSatelliteChange"
                  v-model="addP2pForm.satellite"
                  value-key="id"
                >
                  <el-option
                    v-for="item in addP2pForm.satelliteOption"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <!--终端1波束-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label4')"
                prop="caller.caller_beam"
              >
                <el-select
                  v-model="addP2pForm.caller.caller_beam"
                  value-key="id"
                >
                  <el-option
                    v-for="item in addP2pForm.beamOption"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <!--终端2波束-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label5')"
                prop="caller.caller_beam"
              >
                <el-select
                  v-model="addP2pForm.called.called_beam"
                  value-key="id"
                >
                  <el-option
                    v-for="item in addP2pForm.beamOption"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <!--速率-->
              <!--终端1速率-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label6')"
                prop="caller.caller_speed"
              >
                <el-select
                  v-model="addP2pForm.caller.caller_speed"
                  value-key="value"
                >
                  <el-option
                    v-for="item in addP2pForm.cu1SpeedOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <!--速率-->
              <!--终端2速率-->
              <el-form-item
                class="form-item-padding-right"
                :label="$t('message.p2p.dialog.p2p.create.leftForm.label7')"
                prop="called.called_speed"
              >
                <el-select
                  v-model="addP2pForm.called.called_speed"
                  value-key="value"
                >
                  <el-option
                    v-for="item in addP2pForm.cu2SpeedOption"
                    :key="item.key"
                    :label="item.label"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="subscribe-dialog-div-content-item2">
            <div style="height: 100%">
              <!--输入关键字进行过滤-->
              <div style="text-align: left">
                <el-input
                  size="small"
                  style="margin-bottom: 20px;width: 200px"
                  :placeholder="$t('message.p2p.dialog.p2p.create.filterInputPlaceholder')"
                  v-model="filterText"
                />
                <el-button
                  @click="doTreeFilter"
                  style="margin-left: 15px"
                  size="small"
                  type="primary"
                >
                  查询
                </el-button>
              </div>
              <!--default-expand-all-->
              <el-tree
                show-checkbox
                check-strictly
                node-key="node_key"
                :default-expanded-keys="['root']"
                :expand-on-click-node="false"
                ref="selectDeptTree"
                @node-click="handleTreeNodeClickaaa"
                @check-change="handleDeptTreeCheckChange"
                style="border-radius: 6px;height: 490px;overflow: auto;text-align: left"
                :data="deptTreeForSelectCu"
                :props="deptTreeProps"
                :filter-node-method="filterNode"
              >
                <span
                  style="flex: 1;"
                  slot-scope="{node,data}"
                >
                  <!--class="tree-node-img"-->
                  <img
                    style="width: 1em;padding-left: 5px"
                    :src="$service.renderMethod.getDeptTreeNodeImgSrc(data.node_type, data.kind)"
                  >
                  {{ data.name }}
                </span>
              </el-tree>
            </div>
          </div>
        </div>
        <div slot="footer">
          <el-button
            :loading="submitButtonLoading"
            @click="submitForm('addP2PForm')"
            type="primary"
          >
            <!--确定-->
            {{ $t('message.p2p.dialog.p2p.create.footer.button.submit') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import service from '@/service/service'
import common from '@/common'

export default {
  name: 'P2P',
  computed: {
    deptTreeForSelectCu () {
      return this.$store.getters.deptTreeForSelectCu
    }
  },
  watch: {
    'addP2pForm.caller.selection': {
      deep: true,
      handler: async function (val) {
        if (val) {
          if (val.node_type === 'station') {
            this.addP2pForm.cu1SpeedOption = await this.getCuSpeedOption(val.cus[0].id)
          } else {
            this.addP2pForm.cu1SpeedOption = await this.getCuSpeedOption(val.id)
          }
        } else {
          this.addP2pForm.caller.caller_speed = null
          this.addP2pForm.cu1SpeedOption = []
        }
      }
    },
    'addP2pForm.called.selection': {
      deep: true,
      handler: async function (val) {
        if (val) {
          if (val.node_type === 'station') {
            this.addP2pForm.cu2SpeedOption = await this.getCuSpeedOption(val.cus[0].id)
          } else {
            this.addP2pForm.cu2SpeedOption = await this.getCuSpeedOption(val.id)
          }
        } else {
          this.addP2pForm.called.called_speed = null
          this.addP2pForm.cu2SpeedOption = []
        }
      }
    }
  },
  data () {
    return {
      p2pLoading: false,
      p2pDialogLoading: false,
      submitButtonLoading: false,

      p2pTable: [],

      deptTreeProps: {
        label: 'name',
        children: 'children',
        disabled: (data, node) => {
          if (data.node_type === 'root' || data.node_type === 'dept') {
            return true
          } else if (data.node_type === 'station') {
            return data.cus.length !== 1
          } else {
            return !node.isLeaf
          }
        }
      },

      addP2pVisible: false,
      model: '',

      filterText: '',
      addP2pForm: {
        traffic: {
          label: this.$t('message.p2p.businessType', { businessType: 0 }),
          value: 0
        },
        traffic_option: [
          {
            label: this.$t('message.p2p.businessType', { businessType: 0 }),
            value: 0
          },
          {
            label: this.$t('message.p2p.businessType', { businessType: 1 }),
            value: 1
          }
        ],
        cus: [],
        satellite: '',
        cu1SpeedOption: [],
        cu2SpeedOption: [],
        satelliteOption: [],
        beamOption: [],

        caller: {
          selection: null,
          caller_cu_device: '',
          caller_cu: '',
          caller_beam: '',
          caller_speed: ''
        },
        called: {
          selection: null,
          called_cu_device: '',
          called_cu: '',
          called_beam: '',
          called_speed: ''
        }
      },
      addP2pFormRules: {
        'caller.caller_cu_device': [
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg10'), trigger: 'blur' }
        ],
        'called.called_cu_device': [
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg10'), trigger: 'blur' }
        ],
        traffic: [
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg8'), trigger: 'blur' }
        ],
        satellite: [
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg9'), trigger: 'blur' }
        ],
        'caller.caller_beam': [
          // 请选择终端1波束
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg2'), trigger: 'blur' }
        ],
        'called.called_beam': [
          // 请选择终端2波束
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg2'), trigger: 'blur' }
        ],
        'caller.caller_speed': [
          // 请选择速率
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg1'), trigger: 'blur' }
        ],
        'called.called_speed': [
          // 请选择速率
          { required: true, message: this.$t('message.p2p.dialog.p2p.validate.form.msg1'), trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    let self = this
    self.$nextTick(() => {
      self.getP2pTableData()
    })
  },
  methods: {
    async getCuSpeedOption (cuId) {
      let self = this
      try {
        let response = await self.$store.dispatch('axios', {
          method: 'get',
          url: `/api/abs/devices/cus/${cuId}/support_rates/`
        })
        return response.data.map(speedItem => {
          return {
            label: `${service.miliFormat(speedItem)}`,
            value: speedItem
          }
        })
      } catch (e) {
        return []
      }
    },
    doTreeFilter () {
      let self = this
      self.$refs.selectDeptTree.filter(self.filterText)
    },
    filterNode (value, data) {
      if (!value) return true
      return data.name.toString().indexOf(value) !== -1
    },
    async getP2pTableData () {
      let self = this
      try {
        self.p2pLoading = true
        let resposne = await self.$store.dispatch(`axios`, {
          method: 'get',
          url: '/api/abs/devices/reserve_p2p/'
        })
        self.p2pTable = resposne.data.map(item => {
          return {
            ...item,
            start_time_show: common.convertDateTime(new Date(item.start_time), true),
            end_time_show: common.convertDateTime(new Date(item.end_time), true),
            caller_node_key: `cu_${item.caller_cu}`,
            called_node_key: `cu_${item.called_cu}`
          }
        })
      } finally {
        self.p2pLoading = false
      }
    },
    handleTreeNodeClickaaa (data, node) {
      // console.log(node)
    },
    handleDeptTreeCheckChange (checkData, ifcheck) {
      let self = this
      let selection = self.$refs.selectDeptTree.getCheckedNodes()
      // 根据选择的信息,更新form中的终端信息
      self.setAddP2pCu(checkData, ifcheck)
      // 改变tree的disabled规则,若已经选择了两个终端,则禁止继续选择,取消任意终端后恢复初始
      if (selection.length >= 2) {
        self.deptTreeProps.disabled = (data, node) => {
          if (data.node_type === 'root' || data.node_type === 'dept') {
            return true
          } else {
            if (data.node_type === 'station') {
              return !selection.find(item => item.id === data.id && item.node_type === 'station')
            } else {
              return !selection.find(item => item.device === data.device)
            }
          }
        }
      } else {
        // 重置checkbox的disabled规则
        self.deptTreeProps.disabled = (data, node) => {
          if (data.node_type === 'root' || data.node_type === 'dept') {
            return true
          } else if (data.node_type === 'station') {
            return data.cus.length !== 1
          } else {
            return !node.isLeaf
          }
        }
      }
    },
    setAddP2pCu (data, check) {
      let self = this
      if (check) {
        // 选择节点时
        let checkCu = ''
        if (data.node_type === 'station') {
          checkCu = data.cus[0]
        } else {
          checkCu = data
        }
        if (self.addP2pForm.caller.selection === null) {
          self.addP2pForm.caller.selection = data
          self.addP2pForm.caller.caller_cu_device = checkCu.device
          self.addP2pForm.caller.caller_cu = checkCu.id
        } else if (self.addP2pForm.called.selection === null) {
          self.addP2pForm.called.selection = data
          self.addP2pForm.called.called_cu_device = checkCu.device
          self.addP2pForm.called.called_cu = checkCu.id
        } else {
          console.log('already exist 2 cus')
        }
      } else {
        // 节点被取消选择时
        // 判断caller是否为空,若为空则删除called的信息
        if (self.addP2pForm.caller.selection) {
          if (data.node_type === 'station') {
            if (self.addP2pForm.caller.selection.node_type === 'station' && self.addP2pForm.caller.selection.id === data.id) {
              self.addP2pForm.caller.selection = null
              self.addP2pForm.caller.caller_cu = ''
              self.addP2pForm.caller.caller_cu_device = ''
            } else {
              self.addP2pForm.called.selection = null
              self.addP2pForm.called.called_cu = ''
              self.addP2pForm.called.called_cu_device = ''
            }
          } else {
            if (self.addP2pForm.caller.selection.device === data.device) {
              self.addP2pForm.caller.selection = null
              self.addP2pForm.caller.caller_cu = ''
              self.addP2pForm.caller.caller_cu_device = ''
            } else {
              self.addP2pForm.called.selection = null
              self.addP2pForm.called.called_cu = ''
              self.addP2pForm.called.called_cu_device = ''
            }
          }
        } else if (self.addP2pForm.called.selection) {
          self.addP2pForm.called.selection = null
          self.addP2pForm.called.called_cu = ''
          self.addP2pForm.called.called_cu_device = ''
        }
      }
    },
    handleAddP2pDialogClose () {
      console.log(this.disabled);
      let self = this
      self.$store.commit('setdeptTreeAll', [])
      self.deptTreeProps.disabled = (data, node) => {
        if (data.node_type === 'root' || data.node_type === 'dept') {
          return true
        } else if (data.node_type === 'station') {
          return data.cus.length !== 1
        } else {
          return !node.isLeaf
        }
      }
      self.addP2pForm = {
        ...self.addP2pForm,
        traffic: self.addP2pForm.traffic_option[0],
        cus: [],
        satellite: '',
        speedOption: [],
        satelliteOption: [],
        beamOption: [],
      // 两个波速的  1 和 2 
        caller: {
          selection: null,
          caller_cu_device: '',

          caller_cu: '',
          caller_beam: '',
          caller_speed: ''
        },
        called: {
          selection: null,
          called_cu_device: '',

          called_cu: '',
          called_beam: '',
          called_speed: ''
        }
      }
    },
    async handleP2pCreate () {
      let self = this
      self.p2pDialogLoading = true
      self.addP2pVisible = true
      try {
        await self.$store.dispatch('getDeptTreeAll')
        self.model = 'create'
        // 设置select Option 以及默认值
        // 卫星
        await self.$store.dispatch(`getSatelliteList`)
        self.addP2pForm.satelliteOption = [...self.$store.state.satellite.satelliteList]
        self.addP2pForm.satellite = self.addP2pForm.satelliteOption[0]
        if (self.addP2pForm.satellite) {
          // 波束
          await self.handleAddP2pSatelliteChange()
          self.addP2pForm.caller.caller_beam = self.addP2pForm.beamOption[0]
          self.addP2pForm.called.called_beam = self.addP2pForm.beamOption[0]
        }
      } catch (e) {
        self.addP2pVisible = false
        return
      } finally {
        self.p2pDialogLoading = false
      }
    },
    async handleP2pDelete (row) {
      let self = this
      try {
        // 此操作将永久删除该点对点资源，是否继续？
        await self.$confirm(self.$t('message.p2p.dialog.p2p.validate.message.msg5'), self.$t('message.common.label.prompt'), {
          confirmButtonText: self.$t('message.common.button.confirm'),
          cancelButtonText: self.$t('message.common.button.cancel'),
          type: 'warning'
        })
      } catch (e) {
        return
      }
      //发送删除请求的方法
      await self.$store.dispatch(`axios`, {
        method: 'delete',
        url: `/api/abs/devices/reserve_p2p/${row.id}/`
      })

      self.$message({
        // 点对点资源删除成功
        message: self.$t('message.p2p.dialog.p2p.validate.message.msg6'),
        type: 'success'
      })
      self.getP2pTableData()
    },
    async submitForm (formName) {
      let self = this
      try {
        await self.$refs[formName].validate()
      } catch (e) {
        return
      }
    
      // 校验
      if (self.addP2pForm.caller.selection === null || self.addP2pForm.called.selection === null) {
        // 请选择两个终端s
        self.$message.error(self.$t('message.p2p.dialog.p2p.validate.message.msg1'))
        return
      }
        我们公司在主要做这个东西
      if (formName === 'addP2PForm') {
        let payload = {
          traffic: self.addP2pForm.traffic.value,
          caller_cu: self.addP2pForm.caller.caller_cu,
          caller_beam: self.addP2pForm.caller.caller_beam.id,
          caller_speed: self.addP2pForm.caller.caller_speed.value,

          called_cu: self.addP2pForm.called.called_cu,
          called_beam: self.addP2pForm.called.called_beam.id,
          called_speed: self.addP2pForm.called.called_speed.value
        }
        self.submitButtonLoading = true
        try {
          await self.$store.dispatch('axios', {
            method: 'post',
            url: `/api/abs/devices/reserve_p2p/`,
            data: payload
          })
        } finally {
          self.submitButtonLoading = false
        }
        self.addP2pVisible = false
        // 添加点对点资源成功
        self.$message.success(self.$t('message.p2p.dialog.p2p.validate.message.msg7'))
        self.getP2pTableData()
      }
    },
    async handleAddP2pSatelliteChange () {
      let self = this
      try {
        await self.$store.dispatch(`getBeamOption`, self.addP2pForm.satellite.id)
      } finally {
        self.addP2pForm.caller.caller_beam = null
        self.addP2pForm.called.called_beam = null
      }
      self.addP2pForm.beamOption = [...self.$store.state.beam.beamOption]
    }
  }
}
</script>

<style scoped>
  .subscribe-expand-form-label{
    color: #4e6d9d;
    font-weight: bold;
  }
  .subscribe-expand-form-item{
    width: calc(50% - 10px);
  }
  .subscribe-dialog-div-content{
    margin-top: 30px;
    display: flex;
    flex-flow: row nowrap;
    align-content: center;
  }
  .subscribe-dialog-div-content-item1{
    padding-bottom: 10px;
    flex: 0 0 300px;
    border-radius: 6px;
  }
  .subscribe-dialog-div-content-item2{
    flex: 1 0 350px;
    border-radius: 6px;
  }
  .subscribe-dialog-form-header-container{
    border-bottom: solid 1px #e5e5e5;
  }
  .subscribe-dialog-form-header{
    width: 100%;
    padding: 10px 12px 10px 20px;
    text-align: left;
    font-size: 15px;
    box-sizing: border-box;
    font-weight: bold;
  }
  .form-item-padding-right{
    padding-right: 20px;
  }
</style>
